import { reactive, ref } from "vue";
import instance from "@/api";
import { ElMessage } from "element-plus";
import { useNoPayStore } from "@/stores/useNoPayStore";
import { storeToRefs } from "pinia";
interface moneyInfoType{
    order: string,
    price: number,
    customerName:string
}
const showMoney = ref(false)
let infoRow:any = ''
const moneyInfo = reactive<moneyInfoType>({
    order: "",
    price: 0,
    customerName: ""
})
function confirmMoney(item: any){
    const { order, price, customerName } = item
    const obj = {
        order,
        price,
        customerName
    }
    Object.assign(moneyInfo, obj)
    showMoney.value = true
    infoRow = item
}
async function payFinish(){
    try {
        infoRow.payStatus = 1
        const { id, arrivalTime, serviceStaff } = infoRow
        const noPayStore = useNoPayStore();
        const { tableData, noPayOrderCount } = storeToRefs(noPayStore);
        const send = {
            time: arrivalTime || '',
            staff: serviceStaff ? [Number(serviceStaff)] : [],
            payStatus: 1
        }
        const res = await instance.put(`/api/order/upDateOrder/${id}`, send)
        
        if(res.status !== 200) {
            throw new Error('收款失败')
        }
        
        ElMessage.success('收款成功')
        for (let i = tableData.value.length - 1; i >= 0; i--) {
            if (tableData.value[i].id === id) {
                tableData.value.splice(i, 1);
            }
        }
        noPayStore.setNoPayOrderCount(noPayOrderCount.value - 1)
        showMoney.value = false
    } catch (error) {
        console.error('收款失败:', error)
        ElMessage.error('收款失败')
        infoRow.payStatus = 0
    }
}
export default function(){
    return { showMoney,confirmMoney, moneyInfo, payFinish }
}